#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>


#include "mutex.h"

struct sembuf up = {0, 1, 0};

struct sembuf down = {0, -1, 0};


void mutex_lock(int semaphore_id)
{
  if (semop(semaphore_id, &down, 1) < 0) {
    printf("Error locking semaphore");
    exit(1);
  }
}

void mutex_unlock(int semaphore_id)
{
  if (semop(semaphore_id, &up, 1) < 0) {
    printf("Error unlocking semaphore");
    exit(1);
  }
}

int unsafe_mutex_create() 
{
  int semaphore_id = semget(IPC_PRIVATE, 1, 0600);
  if (semaphore_id < 0) {
    return -1;
  }
  if (semop(semaphore_id, &up, 1) < 0) {
    return -1;
  }
  return semaphore_id;
}

int mutex_create()
{
  int semaphore_id = semget(IPC_PRIVATE, 1, 0600);
  if (semaphore_id < 0) {
    printf("Error creating semaphore");
    exit(1);
  }
  mutex_unlock(semaphore_id); 
  return semaphore_id;
}


void mutex_destroy(int semaphore_id) 
{
  if (semctl(semaphore_id, 0, IPC_RMID) < 0) {
    printf("Error deleting semaphore");
    exit(1);
  }
}


